package nl.hva.three2learn.dao;

import java.util.List;

import nl.hva.three2learn.model.Course;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public final class CourseDaoImpl implements CourseDao {

	@Autowired
	private SessionFactory sessionFactory;
	
	@Override
	public Course findById(long courseId) {
		
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		
		Query q = session.createQuery("from Course c where c.id = :id");
		q.setLong("id", courseId);
		
		Object result = q.uniqueResult();
		
		session.getTransaction().commit();
		
		if (result == null)
			return null;
		
		return (Course) result;
	}

	@Override
	public List<Course> findCoursesLike(String name) {
		
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		
		Criteria criteria = session.createCriteria(Course.class);
		criteria.add(Restrictions.ilike("name", name, MatchMode.ANYWHERE));
	
		List<Course> courses = criteria.list();
		
		session.getTransaction().commit();
		return courses;
	}
	
	@Override
	public List<Course> findAllCourses() { 
		
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		
		Query q = session.createQuery("from Course");
		
		List<Course> courses = q.list();
		
		session.getTransaction().commit();
		
		return courses;
	}
	
	@Override
	public void save(Course course) {
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		session.saveOrUpdate(course);
		session.getTransaction().commit();
	}

	@Override
	public void enable(Course course) {
		
		if (!course.isDisabled())
			return;
		
		course.setDisabled(false);
		
		save(course);
	}
	
	@Override
	public void disable(Course course) {
		
		if (course.isDisabled())
			return;
		
		course.setDisabled(true);
		
		save(course);
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
}
